package net.sourceforge.perforce.core.internal.utils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import org.eclipse.core.resources.IResource;

import java.io.PrintStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;


public class Profiler {
  static List<Profiler> profilers = Lists.newArrayList();

  synchronized public static void dump() {
    for (Profiler profiler : profilers) {
      profiler.dump(System.err);
    }
  }

  private void dump(PrintStream stream) {
    List<String> keys = Lists.newArrayList(counterMap.keySet());
    Collections.sort(keys);

    for (String key : keys) {
      stream.println(profilePoint + "|" + key + ": " + counterMap.get(key));
    }

  }

  private String profilePoint;
  private Map<String, Integer> counterMap = Maps.newHashMap();

  public Profiler(String profilePoint) {
    this.profilePoint = profilePoint;
    profilers.add(this);
  }

  synchronized public void exec(IResource resource) {
    String key = resource.getFullPath().toString();
    exec(key);
  }

  public void exec(String key) {
    Integer count = Integer.valueOf(1);
    if (counterMap.containsKey(key)) {
      count = Integer.valueOf(1 + counterMap.get(key).intValue());
    }
    counterMap.put(key, count);
  }


}
